package com.weixin.web;

import com.agent.entity.PicWord;
import com.agent.service.IPicWordService;
import com.agent.util.Constants;
import com.qq.weixin.mp.aes.XMLParse;
import com.weixin.pojo.AccessToken;
import com.weixin.pojo.ScanInfo;
import com.weixin.service.TokenUtil;
import com.weixin.util.WXUserUtil;
import com.weixin.util.WXUtil;
import com.weixin.util.WxepConstants;
import com.qq.weixin.mp.aes.AesException;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Controller
@RequestMapping(value = "/weixin/")
@Slf4j
public class WXController {

    @Resource(name = "picWordService")
    IPicWordService picWordService;
    @Autowired
    TokenUtil tokenUtil;
    /**
     * 7777报修台 确认请求来自微信服务器
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "verifyUrl",method = RequestMethod.GET)
    public void verifyUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取微信服务器发送过来的四个参数
        //微信加密签名
        String msg_signature = request.getParameter("msg_signature");
        //时间戳
        String timestamp = request.getParameter("timestamp");
        //随机数
        String nonce = request.getParameter("nonce");
        //随机字符串
        String echostr = request.getParameter("echostr");
        log.info("msg_signature is {},timestamp is {},nonce is {},echostr is {}",
                new String[]{msg_signature,timestamp,nonce,echostr});
        PrintWriter out = response.getWriter();
        String result = WxepConstants.REPAIRE_TOKEN;
        try {
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(WxepConstants.REPAIRE_TOKEN, WxepConstants.REPAIRE_ENCODINGAESKEY, WxepConstants.CorpId);
            result =  wxcpt.VerifyURL(msg_signature,timestamp,nonce,echostr);
            log.info("result is {}",result);
        } catch (AesException e) {
            log.error("com.agent.web.WXController.verifyUrl error| ",e);
        }
        out.print(result);
        out.close();
        out = null;
    }


    /**
     * 7777报修台 回调
     * @param request
     * @param response
     * @throws IOException
     */
//    @RequestMapping(value = "verifyUrl",method = RequestMethod.POST)
    public void verifyUrlWithPost(@RequestBody String body, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取微信服务器发送过来的四个参数
        //微信加密签名
        String msg_signature = request.getParameter("msg_signature");
        //时间戳
        String timestamp = request.getParameter("timestamp");
        //随机数
        String nonce = request.getParameter("nonce");
        log.info("post body is {}",body);
        //随机字符串
        String echostr = request.getParameter("echostr");
        log.info("msg_signature is {},timestamp is {},nonce is {},echostr is {}",
                new String[]{msg_signature,timestamp,nonce,echostr});
        PrintWriter out = response.getWriter();
        try {
//            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(WxepConstants.REPAIRE_TOKEN, WxepConstants.REPAIRE_ENCODINGAESKEY, WxepConstants.CorpId);
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt("SE9YP0fpQDMN7CTNjkfVjvyamPtb", "OeWtS5byE8rg2w1zMtkOnMSNAbXIU2KFzA2kGC7VmTl", "ww8797dc9f5a874a42");
            String msg = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, body);
            log.info("msg is {}",msg);
            ScanInfo scanInfo = XMLParse.xmlToBean(msg, ScanInfo.class);
            String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww8797dc9f5a874a42&redirect_uri=7777.thape.com.cn:8080/weixin/to_repair&response_type=code&scope=snsapi_base&agentid=1000003&state=form&engineerId={engineerId}#wechat_redirect";
            String result = wxcpt.EncryptMsg(url.replace("{engineerId}",scanInfo.getScanCodeInfo().getScanResult().split("=")[1]),timestamp,nonce);
            log.info("result is {}",result);
            out.print(result);
            out.close();
            out = null;
        } catch (AesException e) {
            log.error("com.agent.web.WXController.verifyUrl error| ",e);
        }

    }

    /**
     * 售后工作台 确认请求来自微信服务器
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "verifyUrlForAfter",method = RequestMethod.GET)
    public void verifyUrlForAfter(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取微信服务器发送过来的四个参数
        //微信加密签名
        String msg_signature = request.getParameter("msg_signature");
        //时间戳
        String timestamp = request.getParameter("timestamp");
        //随机数
        String nonce = request.getParameter("nonce");
        //随机字符串
        String echostr = request.getParameter("echostr");
        log.info("msg_signature is {},timestamp is {},nonce is {},echostr is {}",
                new String[]{msg_signature,timestamp,nonce,echostr});
        PrintWriter out = response.getWriter();
        String result = WxepConstants.ENGINEER_ENCODINGAESKEY;
        try {
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(WxepConstants.ENGINEER_TOKEN, WxepConstants.ENGINEER_ENCODINGAESKEY, WxepConstants.CorpId);
            result =  wxcpt.VerifyURL(msg_signature,timestamp,nonce,echostr);
            log.info("result is {}",result);
        } catch (AesException e) {
            log.error("com.agent.web.WXController.verifyUrl error| ",e);
        }
        out.print(result);
        out.close();
        out = null;
    }


    /**
     * 售后工作台 确认请求来自微信服务器
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "verifyUrlForMailList",method = RequestMethod.GET)
    public void verifyUrlForMailList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取微信服务器发送过来的四个参数
        //微信加密签名
        String msg_signature = request.getParameter("msg_signature");
        //时间戳
        String timestamp = request.getParameter("timestamp");
        //随机数
        String nonce = request.getParameter("nonce");
        //随机字符串
        String echostr = request.getParameter("echostr");
        log.info("msg_signature is {},timestamp is {},nonce is {},echostr is {}",
                new String[]{msg_signature,timestamp,nonce,echostr});
        PrintWriter out = response.getWriter();
        String result = WxepConstants.MAILLIST_ENCODINGAESKEY;
        try {
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(WxepConstants.MAILLIST_TOKEN, WxepConstants.MAILLIST_ENCODINGAESKEY, WxepConstants.CorpId);
            result =  wxcpt.VerifyURL(msg_signature,timestamp,nonce,echostr);
            log.info("result is {}",result);
        } catch (AesException e) {
            log.error("com.agent.web.WXController.verifyUrl error| ",e);
        }
        out.print(result);
        out.close();
        out = null;
    }

    /**
     * 跳转到报修页面
     * @param code
     * @param state
     * @param
     * @throws IOException
     */
    @RequestMapping(value = "to_repair",method = RequestMethod.GET)
    public String toRepair(@RequestParam("code") String code,@RequestParam("state") String state, Model model,
                           HttpServletRequest request,HttpServletResponse response) throws IOException {
        String userId = WXUserUtil.findCookie(request);
        if("".equals(userId)){
            AccessToken accessToken = WXUtil.getAccessToken(WxepConstants.CorpId,WxepConstants.REPAIRE_SECRET,0);
            if(accessToken !=null ){
                if(accessToken.getExpiresTime() - System.currentTimeMillis()>0){
                    try {
                        userId = WXUserUtil.getUserInfo(accessToken.getToken(), code);
                        log.info("com.weixin.web.WXController.toRepair code is {}, userId is {}",code,userId);
                        Cookie cookie = new Cookie("userId",userId);
                        cookie.setPath("/");
                        response.addCookie(cookie);
                        model.addAttribute("userId",userId);
                    } catch (Exception e) {
                        log.error("WXUserUtil.getUserInfo error |",e);
                    }
                }
            }
        }
        if(WxepConstants.FORM.equals(state)){
            PicWord picWord = new PicWord();
            picWord.setCode("0"); // 只查询选项
            List<PicWord> picWords = picWordService.getPicWordList(picWord);
            if(request.getParameter("engineerId") !=null){
                model.addAttribute("engineerId",request.getParameter("engineerId"));
            }
            String token = tokenUtil.generateToken(Constants.WX_REPAIRE_TOKEN);
            model.addAttribute("token",token);
            model.addAttribute("picWords",picWords);
            return "repair/repair";
        }else if(WxepConstants.LIST.equals(state)){
            return "forward:/weixin/repaire/list?userId="+userId;
        }else if("knowledge".equals(state)){
//            return "forward:/weixin/knowledge/list?condition=";
            return "knowledge/knowledge_list";
        }
        return "";
    }




}
